<template>
    <view class="confirm_box">
        <view v-if="brandOrderList && brandOrderList.length > 0" class="order">
            <!-- 地址 -->
            <view v-if="goodstype != 4" class="address m-b-24">
                <view v-if="addressInfo.name" @click="toChooseAdress">
                    <view class="address_wrapper">
                        <image class="position_icon" src=""></image>
                        <view class="address_content">
                            <view class="font28 h-one isbold">{{ addressInfo.address }}</view>
                            <view class="buyer_info">
                                <text class="m-r-16">{{ addressInfo.name }}</text>
                                <text>{{ dealPhone(addressInfo.mobile) }}</text>
                            </view>
                        </view>
                        <image class="address_into_icon" src="" mode=""></image>
                    </view>
                    <!-- <view class="address-postage">目的国/地区如产生关税及其他费用，需用户自行承担</view> -->
                </view>
                <!-- 还未选择地址 -->
                <view v-else>
                    <view class="address_wrapper">
                        <image class="position_icon" src=""></image>
                        <view class="address_content isbold" @click="toAddAdress">您还未添加收货地址，请点击添加</view>
                        <image class="address_into_icon" src="" mode=""></image>
                    </view>
                </view>
            </view>
            <!-- 商品 -->
            <!-- brandOrderList 购物车商品拆单后品牌商品列表 -->
            <block v-for="(v, i) in brandOrderList">
                <view class="product m-b-24">
                    <view class="product-title m-b-48">
                        <image v-if="v.brandsLogo" class="product_brand_icon" :src="v.brandsLogo">
                        </image>
                        <text v-if="v.comboName || goodstype == 0">
                            {{ v.comboName ? v.comboName : goodstype == 0 ? v.brandsName : "" }}
                        </text>
                    </view>
                    <!-- 普通商品子订单单个商品 -->
                    <view v-if="v.shopData && v.shopData.length == 1">
                        <view class="m-b-48" v-for="(k, j) in v.shopData">
                            <confirmOrderProductItem :pageType="pageType" @openLetter="openLetter" @amount="dealAmount"
                                :i="i" :j="j" :item="k" :introType="3"
                                :modifiableCount="!k.setMealInfoVO && productType != 'product'">
                            </confirmOrderProductItem>
                        </view>
                    </view>
                    <!-- 普通商品子订单多个商品 -->
                    <multipleProduct v-else :data="v.shopData" @tap.native="handlerOpenProductListDialog(v.shopData)">
                    </multipleProduct>
                    <view class="product-pay font28">
                        <view v-show="(v.shopData && v.shopData.length > 0) && goodstype != 4"
                            class="m-b-48 lf lf-between lf-start c-color9">
                            <view class="c-color8">发货时间</view>
                            <!-- 正常发货发货信息 -->
                            <view v-show="deliveryWay == 0" class="delivery_time_text break-word">
                                {{ deliveryDate(v.shopData[0] || {}) }}
                            </view>
                        </view>
                        <view class="lf lf-between lf-start c-color9">
                            <view class="c-color8">留言</view>
                            <view class="product-pay-remark" @tap="handlerInputRemark(v)">
                                <text class="product-pay-remark-text break-word">{{ (v.shopremarks || "").trim() ||
                                    "无留言" }}</text>
                                <image class="remark_icon" src=""></image>
                            </view>
                        </view>
                    </view>
                </view>
            </block>

            <!-- 总费用 -->
            <view class="total-cost view-space font28 m-b-24">
                <view class="lf lf-between lf-center">
                    <view class="c-color8">商品总额</view>
                    <view class="isbold">¥ {{ Number(brandOrderList[0].all_price) }}</view>
                </view>
                <view v-if="goodstype != 4" class="m-t-48 lf lf-between lf-center">
                    <view class="c-color8">总运费</view>
                    <view class="isbold">
                        <!-- brandOrderList[0].all_freightprice==0&& -->
                        <block v-if="brandOrderList[0].all_originalFreight > 0">
                            (
                            <span style="text-decoration: line-through">￥{{
                                Number(brandOrderList[0].all_originalFreight) }}</span>
                            )
                        </block>
                        <!-- 使用优惠券后 商品总额和运费为零时 总运费为0.01 -->
                        ¥ {{ isNotGoodsFeeAndFreightFee ? "0.01" : Number(brandOrderList[0].all_freightprice) }}
                    </view>
                </view>
                <view class="amount_box">
                    <text class="c-color8">合计</text>
                    <text class="isbold">
                        {{ "￥" + Number(totalPriceForShow) }}
                    </text>
                </view>
            </view>

            <!-- 结束 -->
            <view class="pay lf lf-between lf-center">
                <view class="row">
                    <text class="font28 m-r-16">应付金额</text>

                    <view class="c-price-color isbold">
                        <block>
                            <text class="font24">￥</text>
                            <text class="font32">{{ Number(totalPriceForShow) }}</text>
                        </block>
                    </view>
                </view>
                <!-- <view @click="proIntercept(brandOrderList,true,true)" class="btn">确认付款</view> -->
                <!-- <view @click="submitOrder" class="btn">确认付款</view> -->
                <!-- <view @click="openStorePayWayDialog" class="btn">确认付款</view> -->
                <view @click="handlerCombineSubmit" class="btn">确认付款</view>
            </view>
            <!-- 限制 -->
            <uni-popup :showPop="doumeidialog">
                <limitProductItem :title="title" :limitType="limitType" :productType="productType"
                    :limitProduct="limitProduct" @limitClose="limitclose"></limitProductItem>
            </uni-popup>
            <!-- 返回确定 -->
            <screen v-model="open2" @left="submit2" title="" tips="是否放弃本次付款" @right="open2 = false" color="#33c2b4"
                :type="1" buttonLeft="放弃" buttonRight="继续付款"></screen>
        </view>
        <xlf-loading ref="loading" />
        <confirm ref="confirm" />
        <fullScreenTextArea :show.sync="showRemarkDialog" v-model="currentSuborderInfo.shopremarks" maxlength="50" />
        <productListDialog :show.sync="showProductListDialog" :list="currentProductList" :pageType="pageType"
            :deliveryWay="deliveryWay"></productListDialog>
		<paymentPopup ref="paymentPopupRef" @confirm="paymentCompleted" @cancel="failToPay" @fail="failToPay"></paymentPopup>
    </view>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue';
import {
    onLoad,
    onShow,
    onBackPress,
    onUnload
} from "@dcloudio/uni-app";
import { payment } from '@/hooks/usePay/index.ts';
import { mergeGoods } from "@/pages/shopping/cart/util/util.js";
import api from "@/api";
// import { base } from "@/mixins/base.js";
import confirmOrderProductItem from "./components/confirmOrderProductItem.vue";
import screen from "@/pages/shopping/cart/components/screen.vue";
import limitProductItem from "./components/limitProduct.vue";
import fullScreenTextArea from "./components/fullScreenTextArea.vue";
import multipleProduct from "./components/multipleProduct.vue";
import productListDialog from "./components/productListDialog.vue";
import BigNumber from "bignumber.js"; // 浮点数运算插件
import { getPresalesDelivery } from "@/pages/shopping/cart/util/cart.js";
import { loginStatus } from '@/hooks/useLogin';
import { useUserStoreToRefs } from '@/store/useUserStore'
import { useCartLogic } from "@/pages/shopping/cart/composition/useCartLogic.js";
import { useCartStoreToRefs } from "@/store/useCartStore";
import { useOrderStoreToRefs } from "@/store/useOrderStore"
const { addressInfo } = useOrderStoreToRefs()

const { userInfo } = useUserStoreToRefs()
const {
    brandOrderList,
} = useCartStoreToRefs();
const {
    pageType,
    shownlsharedialog,
    dealAmount,
    getAddCard,
    getOrderList,
    getAddress,
    GET_ORDER_LIST,
} = useCartLogic();

// 定义响应式数据
const deliveryWay = ref(0);
const showProductListDialog = ref(false);
const showRemarkDialog = ref(false);
const goodstype = ref(0);
const productType = ref("");
const open2 = ref(false);
const back = ref(true);
const orderNum = ref({});
const prohibit = ref("");
const limitProduct = ref([]);
const doumeidialog = ref(false);
const payway = ref(3);
const title = ref("");
const limitType = ref(1);
const submitTimeLoading = ref(true);
const init1 = ref(false);
const isSubmitting = ref(false);
const texPercentage = ref(0);
const currentSuborderInfo = ref({});
const currentProductList = ref([]);
const remarks = ref("");

// 计算属性
const totalPrice = computed(() => {
    let price = new BigNumber(brandOrderList.value[0]?.all_subtotalPrice) || 0;
    const all_freightprice = Number(brandOrderList.value[0]?.all_freightprice);
    if (price <= 0 && all_freightprice <= 0) {
        price = 0.01;
    }
    return price.toFixed(2);
});

const totalPriceForShow = computed(() => {
    let totalPriceValue = new BigNumber(totalPrice.value);
    return totalPriceValue.toFixed(2);
});

const isNotGoodsFeeAndFreightFee = computed(() => {
    let price = new BigNumber(brandOrderList.value[0]?.all_subtotalPrice) || 0;
    const all_freightprice = Number(brandOrderList.value[0]?.all_freightprice);
    if (price <= 0 && all_freightprice <= 0) {
        return true;
    }
    return false;
});

// 监听 remarks 变化
watch(remarks, () => {
    brandOrderList.value.forEach((item) => {
        item.shopremarks = remarks.value;
    });
});

const dealPhone = (val) => {
    // let phoneArr = val.split("-");
    // let phone = [];
    // if (phoneArr[1].length < 7) {
    //     return val;
    // }
    // for (let i = 0; i < phoneArr[1].length; i++) {
    //     if (i > phoneArr[1].length - 5 || i < 3) {
    //         phone.push(phoneArr[1][i]);
    //     } else {
    //         phone.push("*");
    //     }
    // }
    // return phoneArr[0] + "-" + phone.join("");
    return val
};

const deliveryDate = (goodInfo, orderInfo) => {
    const presalesDelivery = getPresalesDelivery(goodInfo);
    if (presalesDelivery) {
        return presalesDelivery;
    } else if (goodInfo.expressMsg) {
        return goodInfo.expressMsg;
    } else if (goodInfo.spotCustDeliveryMsg || goodInfo.spotDeliveryMsg) {
        return goodInfo.spotDeliveryTimeType == 0
            ? Number(goodInfo.spotDeliveryMsg.split(",")[0].split(":")[0]).toString() +
            "点前下单当天发货，" +
            Number(goodInfo.spotDeliveryMsg.split(",")[0].split(":")[0]).toString() +
            "点后下单则次日发货" +
            (goodInfo.spotDeliveryMsg.split(",")[1] == 1 ? ",节假日顺延" : "")
            : goodInfo.spotCustDeliveryMsg;
    }
};

// 生命周期钩子
onLoad((e) => {
	console.log(e)
    pageType.value = 2;
    productType.value = e.productType;
    // ... existing code ...
    // 以下代码保持原有的异步逻辑
    // this.$nextTick(() => {
    //     this.proIntercept(this.brandOrderList, false);
    // });
    // 转换为组合式语法的异步调用
    nextTick(() => {
        proIntercept(brandOrderList.value, false, false);
    }, 0);
    prohibit.value = e.prohibit;
    const brandInfo = brandOrderList.value[0] || {};
    const shopData = brandInfo.shopData || [];
    const goodsInfo = shopData[0] || {};
    goodstype.value = goodsInfo.saleChannel;
    if (e.remarks) {
        remarks.value = `采样单号：${e.remarks}`;
    }
});

onShow(() => {
    // 提交订单过程中会中断执行跳转到另外页面（例如设置支付密码）然后跳回，导致防止连续点击状态未初始化，不能重新提交订单，所以在此初始化
    isSubmitting.value = false;
});

onBackPress(() => {
    if (back.value) {
        open2.value = true;
        return true;
    }
    return false;
});

onUnload(() => {
    GET_ORDER_LIST([]);
});

// 定义方法
const submitOrder = () => {
    if (isSubmitting.value) return;
    uni.showLoading({
        title: "提交中...",
        mask: true,
    });
    setTimeout(() => {
        isSubmitting.value = true;
        proIntercept(brandOrderList.value, true, true).finally(() => {
            isSubmitting.value = false;
            uni.hideLoading();
        });
    });
};

async function proIntercept(brandOrderList, init, init2) {
    init1.value = init2;
    if (!loginStatus()) {
        loginStatus(() => { }, 'showModal', '请登录')
        isSubmitting.value = false;
        return;
    }
    // 是否有收获地址-农场商品、门店商品不做拦截
    if (![2, 4].includes(brandOrderList[0].shopData[0].saleChannel) && init) {
        if (!addressInfo.value.id) {
            uni.showToast({
                icon: "none",
                title: "您还未选择收货地址！",
            });
            isSubmitting.value = false;
            return;
        }
    }
    return new Promise(async (resolve, reject) => {
        //第一步验证 - 多规格商品提交检查提示
        let proParams1 = {};
        proParams1 = await getOrderNumber(brandOrderList);
        // const verifyRes1 = await submitOrderCheck({
        //     data: proParams1,
        //     type: productType.value
        // });
        const verifyRes1 = await api({
            method: "POST",
            url: `/mall/order/V2021/submitOrderCheck`,
            data: {
                data: proParams1,
                type: productType.value
            },
        });

        if (verifyRes1.length > 0) {
            doumeidialog.value = true;
            await handleList(verifyRes1);

            title.value = "抱歉，以下商品（" + limitProduct.value.length + "件）无法下单购买";
            limitType.value = 1;
            isSubmitting.value = false;
            resolve(false);
            return;
        }
        //第二步验证 - 需修改数量的商品
        let skuCodes = [],
            counts = [];
        const goodsList = brandOrderList.reduce((list, item) => {
            list = list.concat(item.shopData || []);
            return list;
        }, []);
        // 商品去重
        const uniqueList = mergeGoods(
            goodsList,
            (single, repeat) => {
                if (single.skuCode == repeat.skuCode) {
                    single.amount += Number(repeat.amount);
                    return true;
                }
            },
            "skuCode"
        );
        uniqueList.forEach((itemChild) => {
            skuCodes.push(itemChild.skuCode);
            counts.push(itemChild.amount);
        });
        const proParams2 = {};
        proParams2.skuCodes = skuCodes.join();
        proParams2.counts = counts.join();
        // const verifyRes2 = await buyCount(proParams2);
        const verifyRes2 = await api({
            method: "get",
            url: `/mall/goods/V2021/v2/purchaseCheck/buyCount`,
            data: proParams2,
        });
        if (verifyRes2.length > 0) {
            doumeidialog.value = true;
            await handleList(verifyRes2);
            title.value = "请调整商品的购买数量";
            limitType.value = 2;
            isSubmitting.value = false;
            resolve(false);
            return;
        }
        //第三步验证 - 提示需注意的商品-农场商品不做拦截
        if (addressInfo.value.id) {
            proParams2.addressId = addressInfo.value.id;
            proParams2.deliveryWay = deliveryWay.value;
            // const verifyRes3 = await shoppingCarCheck(proParams2);
            const verifyRes3 = await api({
                method: "get",
                url: `/mall/goods/V2021/v2/purchaseCheck/stocksAndLogistics`,
                data: proParams2,
            });
            if (verifyRes3.length > 0) {
                doumeidialog.value = true;

                await handleList(verifyRes3);

                title.value = "请注意以下商品情况，是否继续下单？";
                limitType.value = 3;
                isSubmitting.value = false;
                resolve(false);
                return;
            }
        }
        if (init) {
            console.log("proIntercept11111111", init);

            await checkPass();
            isSubmitting.value = false;
            resolve(true)
            return;
        }
        isSubmitting.value = false;
        resolve(false)
    });
};

// 从商品列表中筛出符合list的指定商品
const handleList = async (list) => {
    return new Promise((resolve, reject) => {
        let arr = [];
        let arr2 = brandOrderList.value.reduce((pre, cur) => {
            return pre.concat(cur.shopData);
        }, []);
        // 商品去重
        arr2 = mergeGoods(
            arr2,
            (single, repeat) => {
                if (single.skuCode == repeat.skuCode) {
                    single.amount += Number(repeat.amount);
                    return true;
                }
            },
            "skuCode"
        );
        arr2.forEach((item) => {
            list.forEach((citem) => {
                if (item.skuCode == citem.skuCode) {
                    item.tipList = citem.tipList;
                    arr.push(item);
                }
            });
        });
        limitProduct.value = arr;
        resolve(true);
    });
}
const paymentPopupRef = ref()
//直接获取订单号提交
const checkPass = async () => {
    return new Promise(async (resolve, reject) => {
        if (orderNum.value.data) return resolve();

        isSubmitting.value = true;

        let needPay = "";
        let res = "";
        let params = "";
        // 商品类型-判断第一条数据
        const goodstype = brandOrderList.value[0].shopData[0].saleChannel;

        // 验证收货地址
        if (!validateAddress()) return resolve();
        params = await getOrderNumber(brandOrderList.value);
		
        params.orders.origin = 1
        needPay = params.orders.totalMoney;
        console.log('goodstype', goodstype)

        //生成订单号
        if (goodstype == 0) {
            res = await api({
                method: "post",
                url: `/mall/order/V2021/v3/submit`,
                data: params,
            });
        }

        //删除购物车中生成订单的商品
        if (!prohibit.value) {
            const carParams = {
                addType: 3,
                arr: brandOrderList.value,
                arrType: 2,
                ifRadio: false
            };
            getAddCard(carParams);
        }
        let source, paySource, payBusinessType;
        source = "shoppingmall";
        payBusinessType = "1";
        paySource = goodstype == 0 ? "6" : "7";
		// #ifndef MP-TOUTIAO
		paymentPopupRef.value.open({
			orderId: res.data,
			payAmount: needPay,
			payBusinessType: payBusinessType,
			// checkOrderType: 'petsService'
		});
		// #endif
		
		// #ifdef MP-TOUTIAO
		const isSuccessed = await payment({
			orderId: res.data,
			payAmount: needPay,
			payBusinessType: payBusinessType,
			// checkOrderType: 'petsService'
		});
		
		if (isSuccessed) {
			uni.showToast({
				title: '支付成功'
			});
			uni.redirectTo({
				url: `/pages/payment/successfulPayment/index?orderId=${orderId.value}`
			});
		} else {
			uni.showToast({
				title: '支付失败'
			});
			uni.redirectTo({
				url: `/pages/petsOrder/petsList/index?orderStatus=0`
			});
		}
		// #endif
		uni.hideLoading()
        // 区分普通和积分商品，积分和普通商品跳转不同支付成功页面
		
        // uni.redirectTo({
        //     url: `/pages/payment/index?payMoney=${needPay}&orderId=${res}&payBusinessType=${payBusinessType}&source=${source}&paySource=${paySource}`,
        //     complete() {
        //         isSubmitting.value = false;
        //         resolve();
        //     }
        // });
    });
}
//支付成功页
const paymentCompleted = async (data) => {
	// 清除缓存
	// addressInfo.value = {};
	// petsInfo.value = [];
	resetUseOrderStore();
	uni.redirectTo({
		url: `/pages/payment/successfulPayment/index?orderId=${data.orderId}`
	});
	
};
const failToPay = () => {
	uni.showToast({
		title: '支付失败'
	});
	uni.redirectTo({
		url: `/pages/petsOrder/petsList/index?orderStatus=0`
	});
};
//农场商品普通商品、门店商品生成订单号所需参数
const getOrderNumber = async (brandOrderList) => {
    return new Promise((resolve, reject) => {
        // 生成orders????
        const orders = {};

        //生成提交的商品信息
        let orderGoods = [];

        // 商品类型
        const goodstype = brandOrderList[0].shopData[0].saleChannel;

        orders["buyerId"] = userInfo.value.id; //买家ID

        // 门店商品不用快递
        if (brandOrderList[0].shopData[0].saleChannel != 4) {
            // 收件信息
            orders["receiverName"] = addressInfo.value.name; //收件人姓名
            orders["receiverMobile"] = addressInfo.value.mobile; //手机人手机号
            if (addressInfo.value.isInternal != 1) {
                orders["receiverProvince"] = addressInfo.value.userAddress ? addressInfo.value.userAddress.province : addressInfo.value.province; //收件省
                orders["receiverCity"] = addressInfo.value.userAddress ? addressInfo.value.userAddress.city : addressInfo.value.city; //收件市
                orders["receiverArea"] = addressInfo.value.area; //收件区
            } else {
                orders["receiverProvince"] = addressInfo.value.country;
                orders["receiverCity"] = "";
                orders["receiverArea"] = "";
            }
            orders["receiverAddress"] = addressInfo.value.address; //收件人地址
            orders["receiverPostcode"] = addressInfo.value.postcode; //收件邮政编码
        }
        orders["goodsMoney"] = brandOrderList[0].all_price; //商品金额
        orders["expressFee"] = brandOrderList[0].all_freightprice; //运费
        // orders['totalMoney'] = brandOrderList[0].all_subtotalPrice; //总金额
        orders["totalMoney"] = totalPrice.value; //总金额
        // 因为之前农场和普通商品供用product字段，现在普通商品使用product、农场使用farm分开需要更换判断方式
        // orders['buyType'] = this.productType = 'product' ? 1 : 2;
        // orders['useScores'] = this.productType = 'product' ? 0 : Number(brandOrderList[0].all_price);
        orders["buyType"] = 1; //购买类型：1-现金购买
        orders["useScores"] = 0; //	使用积分（buy_type为2或3时）
        orders["reduceMoney"] = "0.00"; //优惠金额
        orders["promotionList"] = ""; //促销优惠活动id列表，逗号分隔：空-无促销优惠
        orders["invoiceType"] = 0; //发票类型
        orders["useFCardGoodsListJson"] = "";
        orders["useFoundationCardList"] = "";
        orders["deliveryWay"] = deliveryWay.value; // 暂不发货
        orders["addressId"] = addressInfo.value.isInternal == 1 ? addressInfo.value.id : "";

        //生成备注
        let remarks = [
            {
                presellOn: 1,
                remark: {}
            },
            {
                presellOn: 0,
                remark: {}
            },
            {
                isLettering: 1,
                remark: {}
            }
        ];

        //区分备注格式
        brandOrderList.forEach((item) => {
            item.shopData.forEach((itemChild) => {
                if (itemChild.isLettering && itemChild.letteringMsg) {
                    remarks[2].remark[itemChild.skuCode] = item.shopremarks ? item.shopremarks : "";
                } else if (
                    itemChild.saleType == 3 ||
                    (itemChild.stocks == 0 && itemChild.saleType == 2) ||
                    (itemChild.stocks == 0 && itemChild.prepareStocks > 0)
                ) {
                    remarks[0].remark[itemChild.skuCode] = item.shopremarks ? item.shopremarks : "";
                } else {
                    remarks[1].remark[itemChild.skuCode] = item.shopremarks ? item.shopremarks : "";
                }

                if (goodstype == 0 && !(brandOrderList[0].oneBuyPromotionVO && brandOrderList[0].oneBuyPromotionVO.id)) {
                    orders["remark"] = JSON.stringify(remarks);
                }
                if (goodstype == 0 && brandOrderList[0].oneBuyPromotionVO && brandOrderList[0].oneBuyPromotionVO.id) {
                    orders["remark"] = brandOrderList[0].shopremarks || "";
                }
                if (goodstype == 2) {
                    orders["remark"] = brandOrderList[0].shopremarks || "";
                }

                let iObj = {
                    goodsId: itemChild.id, //产品ID
                    name: itemChild.name ? itemChild.name : itemChild.goodsName, //商品名称
                    price: itemChild.price, //市场价格
                    count: itemChild.amount, //数量
                    thumPic: itemChild.thumPic, //缩略图
                    deliverVolume: itemChild.deliverVolume, // 体积
                    deliverWeight: itemChild.deliverWeight, //发货重量（连包装的重量，g）
                    packageBoxWeight: itemChild.packageBoxWeight, //发货（单个）箱子重量（g）
                    weight: itemChild.weight,
                    skuCode: itemChild.skuCode,
                    isLettering: Boolean(itemChild.isLettering && itemChild.letteringMsg) ? 1 : 0,
                    letteringMsg: itemChild.letteringMsg,
                    deliveryType: itemChild.deliveryType // 发货方式
                };
                if (itemChild.setMealInfoVO) {
                    const setMealInfoVO = itemChild.setMealInfoVO || {};
                    const setMealSkuList = setMealInfoVO.setMealSkuList || [];
                    const goodsInfo =
                        setMealSkuList.find((mealSkuItem) => {
                            return itemChild.skuCode == mealSkuItem.skuCode;
                        }) || {};
                    iObj.price = goodsInfo.currentPrice;
                }
                // #ifdef APP-PLUS
                iObj.orderSourceType = 2;
                // #endif
                // #ifdef MP-WEIXIN
                iObj.orderSourceType = 1;
                // #endif
                if (uni.getSystemInfoSync().platform == "ios") {
                    iObj.phoneType = 2;
                } else if (uni.getSystemInfoSync().platform == "android") {
                    iObj.phoneType = 1;
                } else {
                    iObj.phoneType = 0;
                }
                orderGoods.push(iObj);
            });
        });
        // 商品去重
        orderGoods = mergeGoods(
            orderGoods,
            (single, repeat) => {
                if (single.skuCode == repeat.skuCode) {
                    single.count += Number(repeat.count);
                    return true;
                }
            },
            "skuCode"
        );

        // #ifdef APP-PLUS
        orders.orderSourceType = 2;
        // #endif
        // #ifdef MP-WEIXIN
        orders.orderSourceType = 1;
        // #endif
        if (uni.getSystemInfoSync().platform == "ios") {
            orders.phoneType = 2;
        } else if (uni.getSystemInfoSync().platform == "android") {
            orders.phoneType = 1;
        } else {
            orders.phoneType = 0;
        }
        resolve({
            orders: orders,
            orderGoods: orderGoods,
            promoterId: userInfo.value.rebrandId, // 假设user在userInfo里，需根据实际情况调整
            sourceType: userInfo.value.refereeType, // 假设user在userInfo里，需根据实际情况调整
            brandsRefereeList: brandOrderList[0].brandsRefereeList
        });
    });
}
// 选择地址
const toChooseAdress = () => {
    uni.navigateTo({
        url: "/pages/setting/address/addressManage?checkOrder=true"
    });
};

const toAddAdress = () => {
    uni.navigateTo({
        url: "/pages/addressManagement/addressList/index"
    });
};
// 验证地址是否为当前登录用户所属
const validateAddress = () => {
    if (addressInfo.value && addressInfo.value.userId) {
        return addressInfo.value.userId == userInfo.value.id;
    }
    uni.showToast({
        icon: "none",
        title: "收货地址有误，请重新选择收货地址",
    });
    getAddress();
    return false;
};

const submit2 = () => {
    back.value = false;
    uni.navigateBack({
        delta: 1
    });
};


//提交拦截无法购买的商品相关
const limitclose = async (val) => {
    switch (Number(val)) {
        case 1:
            doumeidialog.value = false;
            break;
        case 2:
            submit2();
            break;
        case 3:
            let arr = brandOrderList.value.reduce((pre, cur) => {
                return pre.concat(cur.shopData);
            }, []);
            let otherArr = [];
            arr.forEach((item) => {
                let status = limitProduct.value.find((citem) => {
                    if (item.skuCode == citem.skuCode) {
                        return true;
                    }
                });
                if (!status) {
                    otherArr.push(item);
                }
            });
            const res = await getOrderList(otherArr);
            if (res) {
                setTimeout(() => {
                    proIntercept(brandOrderList.value, false);
                    doumeidialog.value = false;
                    isSubmitting.value = false;
                }, 1000);
            }
            break;
        case 4:
            if (init1.value) {
                checkPass();
            }

            doumeidialog.value = false;
            break;
    }
}
// 打开留言弹窗
const handlerInputRemark = (suborderInfo) => {
    currentSuborderInfo.value = suborderInfo;
    showRemarkDialog.value = true;
};
// 打开商品清单弹窗
const handlerOpenProductListDialog = (list) => {
    currentProductList.value = list;
    nextTick(() => {
        showProductListDialog.value = true;
    }, 0);
};
// 合并多种提交
const handlerCombineSubmit = () => {
    // 正常支付
    submitOrder();
};

</script>

<style lang="scss" scoped>
@import "@/pages/shopping/cart/common.scss";

.confirm_box {
    position: relative;
}

.bg {
    position: fixed;
    left: 0;
    top: 0;
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100vh;

    >.bg-content {
        margin: 15vh auto 0;
        background-color: #ffffff;
        border-radius: 20rpx;
        width: 80%;

        .b-c-title {
            font-size: 32rpx;
            font-weight: bold;
            text-align: center;
            padding: 20rpx 0;
        }

        .b-c-centent {
            width: 80%;
            max-height: 60vh;
            overflow-y: scroll;
            margin: 0 auto;

            >image {
                width: 100%;
            }
        }

        .b-c-btn {
            font-size: 32rpx;
            text-align: center;
            color: #33c2b4;
            padding: 28rpx 0;
            border-top: 1px solid #e5e5e5;
        }
    }
}

.order {
    min-height: 100vh;
    background-color: #f8f8f8;
    box-sizing: border-box;
    padding: 36rpx;
    padding-bottom: 120rpx;
    padding-bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);

    .delivery_tip {
        margin-bottom: 36rpx;
        display: flex;
        align-items: center;
        color: #7c807f;
        font-size: 24rpx;

        .delivery_tip_icon {
            margin-right: 10rpx;
            width: 32rpx;
            height: 32rpx;
        }
    }

    .view-space {
        padding: 24rpx;
        padding-top: 40rpx;
        background-color: #ffffff;
        border-radius: 12rpx;
    }

    .address {
        padding: 32rpx;
        background-color: #ffffff;
        border-radius: 12rpx;
        line-height: 1;

        .address_wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .address_content {
                flex: 1;
                margin: 0 32rpx;
                color: #1b2120;
                min-width: 0;

                .buyer_info {
                    font-size: 24rpx;
                    margin-top: 16rpx;
                    color: #7c807f;
                }
            }

            .position_icon {
                width: 48rpx;
                height: 48rpx;
            }

            .address_into_icon {
                width: 12rpx;
                height: 20rpx;
            }
        }

        .address-postage {
            color: #b29c62;
            font-size: 24rpx;
            margin-top: 32rpx;
        }

        .address-empty {
            image {
                width: 35rpx;
                height: 35rpx;
            }

            .address_into_icon {
                width: 12rpx;
                height: 20rpx;
            }
        }
    }

    .score_box {
        display: flex;
        align-items: center;
        padding: 32rpx;
        background-color: #ffffff;
        border-radius: 12rpx;
        line-height: 1;

        .score_icon {
            width: 48rpx;
            height: 48rpx;
            margin-right: 16rpx;
        }

        .score_container {
            .score_useful {
                color: #1b2120;
                font-size: 28rpx;

                .score_useful_text {
                    color: #7c807f;
                    font-size: 24rpx;
                }
            }

            .score_consumption {
                margin-top: 16rpx;
                color: #ba6363;
                font-size: 24rpx;
            }
        }
    }

    .product {
        padding: 32rpx;
        background-color: #ffffff;
        border-radius: 12rpx;

        .product-title {
            display: flex;
            align-items: center;
            font-weight: bold;
            color: #7c807f;
            font-size: 28rpx;

            .product_brand_icon {
                margin-right: 8rpx;
                width: 44rpx;
                height: 44rpx;
                border-radius: 8rpx;
            }
        }

        .product-title:empty {
            display: none;
            margin-bottom: 0 !important;
        }

        .product-pay {
            border-top: 1px solid #f8f8f8;
            margin-top: 48rpx;
            padding-top: 48rpx;

            .delivery_time_text {
                width: 73%;
                text-align: right;
            }

            .product-pay-remark {
                width: 73%;
                text-align: right;
                display: flex;
                justify-content: flex-end;
                align-items: center;

                .product-pay-remark-text {
                    flex: 1;
                }

                .remark_icon {
                    margin-left: 8rpx;
                    width: 12rpx;
                    height: 20rpx;
                }
            }

            .product-num {
                border: 1px solid #f6f6f6;
                border-radius: 6rpx;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                text-align: center;
                line-height: 50rpx;
                margin-left: 15rpx;
                font-size: 28rpx;

                >view {
                    width: 66rpx;
                    height: 50rpx;
                    color: #7c807f;
                }

                >view:nth-of-type(2) {
                    width: 140rpx;
                    height: 50rpx;
                    border-left: 1px solid #e4e6e6;
                    border-right: 1px solid #e4e6e6;
                    background: #f4f5f6;
                    font-size: 24rpx;
                    font-weight: bold;
                    color: #1b2120;
                }
            }
        }
    }

    .total-cost {
        padding: 32rpx;
        background-color: #ffffff;
        border-radius: 12rpx;

        .amount_box {
            display: flex;
            justify-content: space-between;
            border-top: 0.5px solid #e4e6e6;
            margin-top: 32rpx;
            padding-top: 32rpx;
            color: #c08e0b;
        }
    }

    .paymend-open {
        max-height: 1300rpx !important;
    }

    .paymend {
        max-height: 400rpx;
        overflow: hidden;
        position: relative;
        transition: all 0.3s;
        background-color: #fff;
        padding-bottom: 120rpx;
        box-sizing: border-box;

        .paymend-title {
            border-bottom: 1px solid #f4f4f4;
            font-weight: bold;
        }

        .paymend-switch {
            text-align: center;
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 80rpx;
            line-height: 80rpx;
            background-color: #fff;
            padding-bottom: 20rpx;

            image {
                width: 35rpx;
                height: 35rpx;
            }
        }
    }

    .pay {
        position: fixed;
        left: 0;
        bottom: 0;
        background-color: #fff;
        // height: 120rpx;
        height: calc(constant(safe-area-inset-bottom) + 120rpx);
        height: calc(env(safe-area-inset-bottom) + 120rpx);
        width: 100%;
        padding: 0 40rpx;
        box-sizing: border-box;
        border-bottom: constant(safe-area-inset-bottom) solid #fff;
        border-bottom: env(safe-area-inset-bottom) solid #fff;

        .btn {
            width: 214rpx;
            height: 76rpx;
            background-color: #33C2B4;
            font-size: 30rpx;
            color: #ffffff;
            text-align: center;
            line-height: 76rpx;
            border-radius: 8rpx;
            // border-radius: 40rpx;
        }
    }
}

.green {
    background-color: #33c2b4;
    color: #fff;
    font-size: 20rpx;
    border-radius: 6rpx;
    padding: 5rpx 10rpx;
}

.scale {
    transform: scale(0.7);
    width: 60rpx;
}

// .replace {
// 	width: 100%;
// 	padding: 32rpx 24rpx 32rpx 32rpx;
// 	box-sizing: border-box;
// 	background: #FFFFFF;
// 	border-radius: 12px;
// 	margin-bottom: 24rpx;

// 	.replace_title {
// 		color: #1b2120;
// 		font-size: 32rpx;
// 		font-weight: bold;
// 		padding-bottom: 24rpx;
// 		border-bottom: 1px solid #F4F4F4;
// 		margin-bottom: 32rpx;
// 	}

// 	.replace_content {
// 		image {
// 			width: 96rpx;
// 			height: 96rpx;
// 			border-radius: 50%;
// 			margin-right: 88rpx;
// 		}

// 		.replace_detail {
// 			min-width: 0;
// 			flex: 1;
// 			view {
// 				color: #7c807f;
// 				font-size: 24rpx;

// 				text {
// 					color: #7c807f;
// 					margin-left: 24rpx;
// 				}

// 				&:first-child {
// 					color: #1b2120;
// 					font-weight: bold;
// 					font-size: 32rpx;
// 					margin-bottom: 4rpx;
// 				}
// 			}
// 		}
// 	}
// }

.customer_container {
    padding: 32rpx;
    display: flex;
    align-items: center;
    background-color: #ffffff;
    margin-bottom: 32rpx;
    border-radius: 12rpx;
    position: relative;

    .customer_image {
        width: 96rpx;
        height: 96rpx;
        border-radius: 50%;
    }

    .customer_info_box {
        flex: 1;
        margin-left: 16rpx;

        .customer_info_name_box {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24rpx;

            .customer_info_name {
                font-size: 32rpx;
                font-weight: bold;
            }
        }

        .customer_info_another {
            display: flex;
            align-items: center;

            .customer_info_another_item {
                height: 20rpx;
                display: flex;
                align-items: center;
                margin-left: 8rpx;
                padding-left: 8rpx;
                font-size: 24rpx;
                font-weight: normal;
                color: #7c807f;
                border-left: 1px solid #cacccc;
            }

            .customer_info_grade {
                width: 92rpx;
                height: 28rpx;
            }

            .customer_info_otherIcon {
                width: 28rpx;
                height: 28rpx;
                margin-right: 8rpx;
            }
        }
    }

    .customer_tag {
        position: absolute;
        right: 0;
        top: 30rpx;
        height: 32rpx;
        padding: 0 12rpx;
        text-align: center;
        line-height: 32rpx;
        font-size: 20rpx;
        color: #33c2b4;
        background-color: rgba(49, 182, 122, 0.15);
        border: 0.5px solid rgba(49, 182, 122, 0.15);
        border-top-left-radius: 16rpx;
        border-bottom-left-radius: 16rpx;
    }
}

.scorll_prevent {
    height: 100%;
    overflow: hidden;
}
</style>
